<template>
  <k-form-modal
    drawer
    width="640px"
    title="操作"
    v-bind="formModalState"
    v-on="formModalEvent"
  >
    <el-tabs v-model="currentTab">
      <el-tab-pane label="线索跟进" name="1">
        <el-form-item label="昵称">{{ state.model.nick_name }}</el-form-item>
        <el-form-item label="手机号">{{ state.model.mobile }}</el-form-item>
        <el-form-item label="跟进次数">{{ state.model.clue_tracking_count }} 次</el-form-item>
        <el-form-item label="线索类型">{{ state.model.sales_user_type }}</el-form-item>
        <el-form-item label="用户姓名"><el-input v-model="state.model.user_name" placeholder="请输入用户姓名（选填）" /></el-form-item>
        <el-form-item label="公司名称"><el-input v-model="state.model.company_name" placeholder="请输入用户公司信息（选填）" /></el-form-item>
        <el-form-item label="公司规模">
          <el-radio-group v-model="state.model.company_size">
            <el-radio v-for="item in ClueCompanySizeOptions" :key="item.value" :label="item.value">{{ item.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="企业微信">
          <el-radio-group v-model="state.model.enterprise_wechat">
            <el-radio v-for="item in wechatStatus" :key="item.value" :label="item.value">{{ item.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="成交意向">
          <el-radio-group v-model="state.model.deal_intent">
            <el-radio v-for="item in dealIntentOptions" :key="item.value" :label="item.value">{{ item.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="跟进说明">
          <el-input
            v-model="state.model.followup_notes"
            type="textarea"
            :rows="3"
            placeholder="可以输入用户的公司信息联系方式/用户的需求及要求/用户弃用的原因/有无成交意向的解释说明等（选填）"
          />
        </el-form-item>
      </el-tab-pane>
      <el-tab-pane label="用户信息" name="2">
        <div class="info-wrapper">
          <div v-for="item in userInfo" :key="item.prop" class="item">
            <div class="label">{{ item.label }}</div>
            <div class="value">
              {{ item.value }}
            </div>
          </div>
        </div>
        <h5 class="mb-5">历史订单</h5>
        <k-table v-bind="tableState" :data="historyDataList">
          <template #pagination></template>
        </k-table>
      </el-tab-pane>
      <el-tab-pane label="跟进历史" name="3">
        <k-table v-bind="followTableState" :data="dataList">
          <template #pagination></template>
        </k-table>
      </el-tab-pane>
      <el-tab-pane label="销售订单" name="4">
        <h5 class="mb-5">销售订单</h5>
        <k-table v-bind="saleTableState" :data="dataList">
          <template #pagination></template>
        </k-table>
      </el-tab-pane>
    </el-tabs>
  </k-form-modal>
</template>

<script setup lang="ts">
import { ref, computed, reactive } from 'vue';
import { ElMessage } from 'element-plus';

import { useHistoryTableList, ClueCompanySizeOptions, dealIntentOptions, wechatStatus, platformOptions, useFollowLogsList, useSalesLogsList } from '../hooks/use-table';
import { useFormModal } from '@crud/index';
import { getSalesUserInfo, getFollowLogs, getSalesOrderLogs, addClueFollow } from '@/api/crm-kgj/sales';
import dayjs from 'dayjs';

const emits = defineEmits(['after-submit']);
const formRef = ref();
const dataList = ref([]);
const currentTab = ref('1');
const salesUserId = ref();
/** 历史订单数据 */
const historyDataList = ref([]);
const { state: tableState } = useHistoryTableList({});

/** 跟进历史数据 */
const followLogsList = ref([]);
const { state: followTableState } = useFollowLogsList({});
/** 销售订单数据 */
const salesOrderList = ref([]);
const { state: saleTableState } = useSalesLogsList({});
const userInfo = reactive([
  { label: '昵称', value: '', prop: 'nick_name' },
  { label: '手机号', value: '', prop: 'mobile' },
  { label: '注册渠道', value: '', prop: 'platform', type: 'platform' },
  { label: '注册时间', value: '', prop: 'add_time', type: 'date' },
  { label: '到期版本', value: '', prop: 'product_name' },
  { label: '到期时间', value: '', prop: 'user_end_time', type: 'date' },
  { label: '最后访问时间', value: '', prop: 'last_login_time', type: 'date' }
]);

const { state, formModalState, formModalEvent, ...methods } = useFormModal({
  formRef,
  model: {
    sales_user_id: null,
    user_name: '',
    company_name: '',
    company_size: -1,
    enterprise_wechat: 0,
    deal_intent: 0,
    followup_notes: ''
  },
  getParams: (model) => model,
  onShow: async (mode = 0, data: any) => {
    const { sales_user_id } = data;
    salesUserId.value = sales_user_id;
    /** 获取用户信息 */
    const userInfoRes = await getSalesUserInfo({ sales_user_id });
    if (!userInfoRes.err) {
      // 配置线索跟进数据
      state.model = { ...state.model.params, ...userInfoRes.data, sales_user_id };
      userInfo.forEach((item) => {
        const { type } = item;
        const value = userInfoRes.data[item.prop];
        if (type === 'platform') {
          item.value = platformOptions.find((e) => e.value === value)?.label;
        } else if (type === 'date') {
          item.value = dayjs.unix(value).format('YYYY-MM-DD');
        } else {
          item.value = value;
        }
      });
      /** 配置跟进历史table数据 */
      historyDataList.value = userInfoRes.data?.order_list;
      handleGetOtherTableData();
    }
  },
  onSubmit: () => {
    handleSaveClue();
  }
});
/** 获取其他表格的数据 */
const handleGetOtherTableData = async () => {
  const params = { sales_user_id: salesUserId.value };
  const followLogsRes = await getFollowLogs(params);

  if (!followLogsRes.err) {
    followLogsList.value = followLogsRes.data;
  }
  const salesOrderRes = await getSalesOrderLogs(params);
  if (!salesOrderRes.err) {
    salesOrderList.value = salesOrderRes.data;
  }
};
/** 保存跟进线索 */
const handleSaveClue = async () => {
  const { sales_user_id, followup_notes, company_name, user_name, company_size, enterprise_wechat, deal_intent } = state.model;
  const res = await addClueFollow({
    sales_user_id,
    followup_notes,
    company_name,
    user_name,
    company_size,
    enterprise_wechat,
    deal_intent
  });
  if (!res.err) {
    ElMessage.success('更新成功');
    emits('after-submit');
  }
  return res;
};
defineExpose({
  show: methods.show
});
</script>
<style lang="scss" scoped>
.info-wrapper {
  display: flex;
  flex-wrap: wrap;
  font-size: 14px;

  .item {
    display: flex;
    flex: 50% 0;
    margin-bottom: 20px;

    .label {
      width: 100px;
      margin-right: 16px;
      color: var(--text-3);
      text-align: right;
    }
  }
}
</style>
